package com.zhongfl.crm.lixiao.batch.service;

import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.request.revisitlog.LXCommentsSaveRequest;
import com.heptagram.lixiao.bean.request.revisitlog.LXRevisitLog;
import com.heptagram.lixiao.bean.response.revisitlog.LXCommentSaveResponse;
import com.heptagram.lixiao.bean.response.revisitlog.LXRevisitLogSaveResponse;
import com.zhongfl.crm.enums.boss.OrderMemorandumTypeEnum;
import com.zhongfl.crm.lixiao.bean.resolve.OrderMemorandum2RevisitLogResolver;
import com.zhongfl.crm.lixiao.config.MailConfigInfo;
import com.zhongfl.crm.lixiao.mapper.LXOrderMapper;
import com.zhongfl.crm.mail.MailService;
import com.zhongfl.crm.mail.bean.MailMessage;
import com.zhongfl.crm.mail.bean.MailMessageBuilder;
import com.zhongfl.crm.mail.enums.MailTypeEnum;
import com.zhongfl.crm.model.boss.OrderMemorandum;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.CustomerOrderService;
import com.zhongfl.crm.service.boss.LXRevisitLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * boss备忘录 同步到励销service
 *
 * @author tiantian
 * @date 2018/6/28 11:46
 */
@Service
@Slf4j
public class OrderRevisitLogSyncFromBoss2LXService {
    @Resource
    private LXRevisitLogService lxRevisitLogService;
    @Resource
    private LiXiaoService liXiaoService;
    @Resource
    private MailConfigInfo mailConfigInfo;
    @Resource
    private MailService mailService;
    @Resource
    private LXOrderMapper lxOrderMapper;
    @Resource
    private LxUserService lxUserService;
    @Resource
    private CustomerOrderService customerOrderService;

    public void sync(OrderMemorandum task) {
        if (Objects.isNull(task)) {
            return;
        }

        try {
            log.info("跟进记录id: {} 开始同步", task.getId());

            // 1.本地同步到励销
            OrderMemorandum2RevisitLogResolver resolver = new OrderMemorandum2RevisitLogResolver(lxOrderMapper, lxUserService, lxRevisitLogService, liXiaoService.getAttachmentService(),customerOrderService);

            Long lxRevisitLogId = null;
            if (task.getType().equals(OrderMemorandumTypeEnum.REMARK)) {
                LXRevisitLog lxRevisitLog = resolver.resolve(task);
                LXRevisitLogSaveResponse lxRevisitLogSaveResponse = liXiaoService.getRevisitLogService().saveRevisitLog(lxRevisitLog);
                if (Objects.nonNull(lxRevisitLogSaveResponse)) {
                    lxRevisitLogId = lxRevisitLogSaveResponse.getData().getId();
                }
            } else if (task.getType().equals(OrderMemorandumTypeEnum.COMMENT)) {
                LXCommentsSaveRequest commentsSaveRequest = resolver.resolveComment(task);
                LXCommentSaveResponse lxCommentSaveResponse = liXiaoService.getRevisitLogService().saveCommentLog(commentsSaveRequest);
                if (Objects.nonNull(lxCommentSaveResponse)) {
                    lxRevisitLogId = lxCommentSaveResponse.getData().getId();
                }
            }

            Thread.sleep(1000);
            log.info("跟进记录id: {} 同步励销成功, 开始回写lxLogId ", task.getId());

            // 2.更新励销ID入表, 防止再摘下来
            if (Objects.nonNull(lxRevisitLogId)) {
                OrderMemorandum updateMemorandum = new OrderMemorandum();
                updateMemorandum.setId(task.getId());
                updateMemorandum.setLxRevisitLogId(lxRevisitLogId);
                updateMemorandum.setModifiedBy("BOSS系统");
                lxRevisitLogService.updateById(updateMemorandum);
                log.info("跟进记录id: {} 已回写 lxLogId: {} 完成", task.getId(), lxRevisitLogId);
            }
        } catch (Exception ex) {
            log.error("记录ID: id:{} 同步出错", task.getId(), ex);
            sendErrorEmail(task, ex.getMessage());
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    private void sendErrorEmail(OrderMemorandum task, String errorMsg) {
        if (Objects.isNull(task)) {
            return;
        }

        try {
            MailMessage mailMessage = MailMessageBuilder.builder()
                .mailTypeEnum(MailTypeEnum.BOSS_ORDER_MEMORANDUM_SYNC_ERROR)
                .subject("Boss跟进->励销 同步异常通知-" + mailConfigInfo.getActiveProfiles())
                .to(mailConfigInfo.getDefaultTo())
                .addData("title", "Boss跟进->励销 同步异常通知")
                .addData("data", task)
                .addData("msg", errorMsg)
                .build();

            mailService.send(mailMessage);
        } catch (Exception ex) {
            log.error("发送邮件异常: {}", ex.getMessage(), ex);
        }
    }

}
